<template>
  <el-dialog
    v-model="dialogVisible"
    title="保存场景"
    :width="700"
    append-to-body
    @close="handleClose"
    custom-class="center-detail"
  >
    <JLForm
      ref="formRef"
      :form-config="formConfig"
      :form-data="formData"
      :form-item-config="formItemConfig"
    >
      <template #coverSlot>
        <div class="cover-wrap">
          <div v-if="cover" class="upload-cover-wrap">
            <el-image :src="cover" class="avatar" fit="cover" />
            <div class="tip-wrap">将当前视角设置为场景封面</div>
          </div>
          <el-image v-else :src="sceneStore.sceneDetail.actCover" class="avatar" fit="cover" />
        </div>
      </template>
    </JLForm>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button color="#0560FD" type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useForm } from './useForm';
import { JLForm } from '@jl/element-plus';
import { saveSceneConfig, updateScene } from '@/api/scene';
import { commonUpload, tdtSearch, tdtGeocoderSearch } from '@/api/common';
import { CommonUploadResp } from '@/api/common/types';
import { messageUtil } from '@jl/element-plus/utils';
import { useSceneStore } from '@/store/scene';
import { retFilePath, myHtml2canvas, setTreeSortField, flattenTreeIterative } from '@/utils';
import { operateInvalidPoi } from '@/service';
import { cloneDeep } from 'lodash';

defineOptions({
  name: 'SceneFirstSaveDialog',
});

const sceneStore = useSceneStore();
const { formRef, formConfig, formData, formItemConfig, proListRun } = useForm();
const dialogVisible = ref<boolean>(true);
const emit = defineEmits(['closeHandle']);
const cover = ref<string>('');

const handleClose = () => {
  emit('closeHandle', false);
};

onMounted(() => {
  proListRun({
    params: {
      index: 1,
      pageSize: 1000,
      blurStr: '',
      state: -1,
    },
  });
  formData.value.activityName = sceneStore.sceneDetail.activityName;
  formData.value.projectId = sceneStore.sceneDetail.projectId;
  formData.value.actDesp = sceneStore.sceneDetail.actDesp;
  if (!sceneStore.sceneDetail.actCover) {
    myHtml2canvas(document.getElementById('cesiumContainer') as any).then(async (file: any) => {
      const res: CommonUploadResp = await commonUpload(file);
      cover.value = retFilePath(res.files[0].refAddress);
    });
  }
});

function save() {
  const { cimInstance } = window;
  if (!sceneStore.sceneDetail) return;
  formRef.value?.getInstance().validate(async (valid, fields) => {
    if (valid) {
      await saveBasic();
      console.log('场景导出参数-------------------', cimInstance.api.exportCurrentScene());

      console.log('数结构', sceneStore.layerTree);
      operateInvalidPoi();
      const layerTree = cloneDeep(sceneStore.layerTree);
      // 设置排序字段
      setTreeSortField(layerTree);
      console.log('---------setTreeSortField--------', layerTree);
      const layerList = flattenTreeIterative(layerTree);
      for (const list of layerList) {
        if (!list.name) {
          messageUtil.warning('图层名称不能为空，请修正后再保存');
          return;
        }
        // 除了div,后续属性不再存储
        if (!['div'].includes(list.type)) {
          list.attr = null;
          delete list.attr;
        }
        if (list.attr) {
          if (list.attr.position) {
            list.attr.position = list.attr.position.map((v: any) => Number(v));
          }
        }
        if (list?.json?.hasOwnProperty('zoomTo')) {
          delete list?.json.zoomTo;
        }
      }

      const configJson = {
        cimup: cimInstance.api.exportCurrentScene(),
        layer: layerList,
        globalEffect: sceneStore.globalEffectSetting,
      };

      const formData = new FormData();
      formData.append('activityId', sceneStore.sceneDetail.activityId);
      formData.append('configJson', JSON.stringify(configJson));
      saveSceneConfig({ data: formData }).then(() => {
        messageUtil.success('保存成功');
        sceneStore.sceneDetail.configJson = JSON.stringify(configJson);
        sceneStore.getVersionList();
        emit('closeHandle', true);
      });
    }
  });
}

async function saveBasic() {
  if (!sceneStore.sceneDetail) return;
  const fData = new FormData();
  fData.set('activityId', sceneStore.sceneDetail.activityId);
  fData.set('activityName', formData.value.activityName);
  fData.set('projectId', formData.value.projectId || '');
  fData.set('actViewAngle', sceneStore.sceneDetail.actViewAngle || '');
  fData.set('actDesp', formData.value.actDesp || '');
  fData.set('actCover', sceneStore.sceneDetail.actCover || cover.value);
  fData.set('conifgId', sceneStore.sceneDetail.conifgId || '');
  const param = {
    data: fData,
  };
  await updateScene(param);
  sceneStore.sceneDetail.activityName = formData.value.activityName;
  sceneStore.sceneDetail.projectId = formData.value.projectId;
  sceneStore.sceneDetail.actDesp = formData.value.actDesp;
  sceneStore.sceneDetail.actCover = sceneStore.sceneDetail.actCover || cover.value;
}
</script>

<style lang="less" scoped>
:deep(.el-textarea__inner) {
  height: 96px;
}
.cover-wrap {
  position: relative;
  width: 100%;
  height: 237px;
  border-radius: 4px;
  overflow: hidden;
  .el-image {
    width: 100%;
    height: 100%;
  }
  .upload-cover-wrap {
    width: 100%;
    height: 100%;
    .tip-wrap {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 35px;
      background: fade(#0560fd, 60%);
      display: flex;
      justify-content: center;
      align-items: center;
      color: #e8e8e8;
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
